package cn.wolfcode.luowowo.website.resolver;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotion.UserParm;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义登陆用户参数解析器
 * 满足两个条件，1.UserInfo类型 2.已经登陆的
 *
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{

    @Reference
    private IUserInfoRedisService userInfoRedisService;
    /**
     * 这个方法表示当前要解析什么类型的参数
     * 返回true就代表支持指定类型
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType() == UserInfo.class && methodParameter.hasParameterAnnotation(UserParm.class);
    }


    //表示如果是需要解析执行的逻辑
    //如果成功解析的话会帮我们把user对象注入UserInfo类里面
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String token = CookieUtil.getToken(request, response);
        UserInfo user = userInfoRedisService.getRedisUserByToken(token);
        return user;
    }
}
